<?php
// +----------------------------------------------------------------------
// | 萤火商城系统 [ 致力于通过产品和服务，帮助商家高效化开拓市场 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2023 https://www.yiovo.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed 这不是一个自由软件，不允许对程序代码以任何形式任何目的的再发行
// +----------------------------------------------------------------------
// | Author: 萤火科技 <admin@yiovo.com>
// +----------------------------------------------------------------------
declare (strict_types = 1);

namespace app\api\model\ding;

use app\api\model\ding\Order as OrderModel;
use app\api\service\Message as MessageWechatService;
use app\api\service\User as UserService;
use app\common\model\ding\OrderGoods as OrderGoodsModel;
use app\common\service\order\Printer as PrinterService;
use app\store\service\wxapp\Message as MessageService;
use think\facade\Db;

/**
 * 商品评价模型
 * Class Article
 * @package app\api\model
 */
class OrderGoods extends OrderGoodsModel
{
    /**
     * 隐藏字段
     * @var array
     */
    protected $hidden = [
        'is_delete',
        'store_id',
        'update_time',
    ];

    public function increased($orderId, array $data)
    {
        $userId = UserService::getCurrentLoginUserId(true);

        $cartList = Db::name('ding_cart')->alias('c')
            ->join('ding_food f', 'f.food_id=c.food_id')
            ->where('c.user_id', $userId)
            ->where('c.shop_id', $data['shop_id'])
            ->where('c.food_num', '>', 0)
            ->field('c.food_num as total_num,f.price,f.food_id,f.image_id,f.name')
            ->select()->toArray();
        $shop = Db::name('store_shop')->where('shop_id', $data['shop_id'])->field('need_queu,shop_name')->find();
        if ($cartList) {

            //菜单记录
            $menu['user_id']     = $userId;
            $menu['order_id']    = $orderId;
            $menu['store_id']    = self::$storeId;
            $menu['create_time'] = time();

            $menu_id = Db::name('ding_order_menu')->insertGetId($menu);

            $dataset     = [];
            $total_num   = 0;
            $total_price = 0;
            foreach ($cartList as $key => $order) {
                $order['total_price']     = $order['total_num'] * $order['price'];
                $order['total_pay_price'] = $order['total_num'] * $order['price'];
                $order['food_name']       = $order['name'];
                $order['order_id']        = $orderId;
                $order['menu_id']         = $menu_id;
                $order['store_id']        = self::$storeId;
                $dataset[]                = $order;
                $total_num += $order['total_num'];
                $total_price += $order['total_num'] * $order['price'];
            }
            $this->saveAll($dataset);

            if ($shop['need_queu'] == 0) {
                //是否需要打印
                $this->sDaying([$menu_id]);
            }

            Db::name('ding_order_menu')->where('menu_id', $menu_id)
                ->update(['total_num' => $total_num, 'total_price' => $total_price]);

            Db::name('ding_cart')->where('user_id', $userId)->where('shop_id', $data['shop_id'])->delete();

        }

        $clerks = Db::name('store_shop_clerk')->where('shop_id', $data['shop_id'])
            ->group('user_id')
            ->where('reserve_msg', 1)
            ->select()->toArray();

        $order = Db::name('ding_order')->where('id', $orderId)->field('id,user_id,shop_id,real_name,mobile,date,time,name')->find();
        foreach ($clerks as $key => $value) {
            $opend_id = $value['oauth_id'];
            if ($opend_id) {
                // 执行发送

                $MessageService         = new MessageService;
                $content['template_id'] = 'f_-0dcAA9sSC4KM1JzMgwgoyaljyxe3yrnig7wN8sNQ';
                $content['page']        = 'pagesNew/order/menu-detail?orderId=' . $orderId . '&shopId=' . $data['shop_id'];

                $content['data']['time4'] = Date('Y-m-d H:i');
                //$content['data']['phrase9'] = $order['real_name'];
                $content['data']['phone_number14'] = $order['mobile'];
                $content['data']['time16']         = $order['date'] . ' ' . $order['time'];
                $content['data']['thing3']         = '点菜';

                //暂时注释
                $MessageService->send($opend_id, $content);

            }
        }

        //发送订阅通知给小程序用户

        $MessageService = new MessageWechatService;

        $params   = [];
        $opend_id = Db::name('user_oauth')->where('user_id', $order['user_id'])->value('oauth_id');
        $shop     = Db::name('store_shop')->where('shop_id', $order['shop_id'])->field('shop_name')->find();

        $params['template_id'] = 'pyJ0GA8UWhXKmkw-nz5KeG5rJ2f9thgk4esfC6indHs';
        $params['page']        = 'pagesNew/user/order/detail?orderId=' . $order['id'] . '&shopId=' . $order['shop_id'];
        $params['data']        = [
            'thing6'  => ['value' => $shop['shop_name']],
            'thing2'  => ['value' => $cartList[0]['name'] . '*' . $cartList[0]['total_num'] . '等'],
            'thing14' => ['value' => $order['name']],
        ];

        $MessageService->send($opend_id, $params);

        return true;
    }

    public function increasedClerk($orderId, array $data)
    {
        $userId = UserService::getCurrentLoginUserId(true);

        $cartList = Db::name('ding_cart')->alias('c')
            ->join('ding_food f', 'f.food_id=c.food_id')
            ->where('c.user_id', $userId)
            ->where('c.shop_id', $data['shop_id'])
            ->where('c.food_num', '>', 0)
            ->field('c.food_num as total_num,f.price,f.food_id,f.image_id')
            ->select()->toArray();
        if ($cartList) {

            //菜单记录
            $menu['user_id']     = $userId;
            $menu['order_id']    = $orderId;
            $menu['store_id']    = self::$storeId;
            $menu['create_time'] = time();

            $menu_id = Db::name('ding_order_menu')->insertGetId($menu);

            $dataset     = [];
            $total_num   = 0;
            $total_price = 0;
            foreach ($cartList as $key => $order) {
                $order['total_price']     = $order['total_num'] * $order['price'];
                $order['total_pay_price'] = $order['total_num'] * $order['price'];
                $order['order_id']        = $orderId;
                $order['menu_id']         = $menu_id;
                $order['store_id']        = self::$storeId;
                $dataset[]                = $order;
                $total_num += $order['total_num'];
                $total_price += $order['price'];
            }

            Db::name('ding_order_menu')->where('menu_id', $menu_id)->update(['total_num' => $total_num, 'total_price' => $total_price]);

            Db::name('ding_cart')->where('user_id', $userId)->where('shop_id', $data['shop_id'])->delete();

            $this->saveAll($dataset);
        }

        return true;
    }
    //用户自主打印
    public function sDaying(array $menuIds = [])
    {

        // 设置更新条件

        $where[] = ['id', 'in', $menuIds];
        Db::name('ding_order_menu')->where('menu_id', 'in', $menuIds)->where('is_daying', 0)->update(['is_daying' => 1]);

        $orderId = Db::name('ding_order_menu')->where('menu_id', 'in', $menuIds)->value('order_id');

        $detail = OrderModel::getDetail($orderId);

        // 小票打印
        //打印机
        $printerId = Db::name('printer')->where('shop_id', $detail['shop_id'])->value('printer_id');
        if ($printerId) {
            // 实例化打印机驱动
            $Printer = new PrinterService;
            // 手动打印小票
            $status = $Printer->printEvent($detail, $printerId, $menuIds);

        }

        // 更新记录
        return true;
    }
    //确认菜单
    public function sUpdate(array $menuIds = [])
    {

        // 设置更新条件

        $where[] = ['id', 'in', $menuIds];
        $menus   = Db::name('ding_order_food')->where('menu_id', 'in', $menuIds)->select()->toArray();
        $menu    = Db::name('ding_order_menu')->where('menu_id', 'in', $menuIds)->find();
        if ($menu['status'] == 1) {
            return true;
        }
        Db::name('ding_order_menu')->where('menu_id', 'in', $menuIds)->update(['status' => 1]);
        Db::name('ding_order_food')->where('menu_id', 'in', $menuIds)->update(['status' => 1]);
        $total_price = Db::name('ding_order_food')->where('menu_id', 'in', $menuIds)->sum('total_pay_price');

        $orderId = Db::name('ding_order_menu')->where('menu_id', 'in', $menuIds)->value('order_id');

        $detail = OrderModel::getDetail($orderId);

        if ($total_price > 0) {
            Db::name('ding_order')->where('id', $orderId)->update(['pay_status' => 10, 'total_price' => $detail['total_price'] + $total_price, 'pay_price' => $detail['pay_price'] + $total_price]);

        }

        $shop = Db::name('store_shop')->where('shop_id', $detail['shop_id'])->field('need_queu')->find();

        if ($shop['need_queu'] == 1) {

            //打印机
            $printerId = Db::name('printer')->where('shop_id', $detail['shop_id'])->value('printer_id');
            if ($printerId) {
                // 实例化打印机驱动
                $Printer = new PrinterService;
                // 手动打印小票
                $status = $Printer->printEvent($detail, $printerId, $menuIds);

            }

        }

        // 更新记录
        return true;
    }
    /**
     * 获取文章列表
     * @param int $categoryId
     * @param int $limit
     * @return \think\Paginator
     * @throws \think\db\exception\DbException
     */
    public function getList(int $orderId = 0)
    {
        // 检索查询条件
        $filter                   = [];
        $orderId > 0 && $filter[] = ['order_id', '=', $orderId];
        $menus                    = Db::name('ding_order_menu')->alias('m')
            ->join('user', 'user.user_id=m.user_id')
            ->where('m.order_id', $orderId)
            ->field('m.*,user.nick_name')
            ->select()->toArray();
        foreach ($menus as $key => $menu) {
            $menus[$key]['create_time'] = Date('Y-m-d H:i:s', $menu['create_time']);
            $menus[$key]['goods']       = $this->with(['food.image'])

                ->where($filter)

                ->where('menu_id', '=', $menu['menu_id'])
                ->where('is_delete', '=', 0)
                ->order(['create_time' => 'desc'])
                ->select()->toArray();
        }
        // 获取列表数据
        return $menus;
    }
    /**
     * 获取文章列表
     * @param int $categoryId
     * @param int $limit
     * @return \think\Paginator
     * @throws \think\db\exception\DbException
     */
    public function getListAll(int $orderId = 0)
    {
        // 检索查询条件
        $filter                   = [];
        $orderId > 0 && $filter[] = ['order_id', '=', $orderId];
        $list                     = $this->with(['food.image'])

            ->where($filter)
            ->where('status', 1)
            ->where('is_delete', '=', 0)
            ->order(['create_time' => 'desc'])
            ->select()->toArray();

        return $list;
    }
/**
 * 获取文章列表
 * @param int $categoryId
 * @param int $limit
 * @return \think\Paginator
 * @throws \think\db\exception\DbException
 */
    public function getListAllWait(int $orderId = 0)
    {
        // 检索查询条件
        $filter                   = [];
        $orderId > 0 && $filter[] = ['order_id', '=', $orderId];
        $list                     = $this->with(['food.image'])

            ->where($filter)
            ->where('is_delete', '=', 0)
            ->where('status', 0)
            ->order(['create_time' => 'desc'])
            ->select()->toArray();

        return $list;
    }
}
